package com.tanhua.dubbo.api.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Friend;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.mapper.UserInfoMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfo findById(Long id) {
        return userInfoMapper.selectById(id);
    }

    @Override
    public IPage<UserInfo> findByPage(Integer page, Integer pagesize) {
        return userInfoMapper.selectPage(new Page<>(page,pagesize),null);
    }

    @Override
    public void freezeUser(UserInfo userInfo) {
        userInfo.setUserStatus("2");
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public void unfreezeUser(UserInfo userInfo) {
        userInfo.setUserStatus("1");
        userInfoMapper.updateById(userInfo);
    }

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 随机查询10条数据
     * (排除自己)
     * @param userId
     * @return
     */
    @Override
    public List<UserInfo> queryRandom10(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        List<Long> list = new ArrayList<>();
        for (Friend friend : friendList){
            list.add(friend.getFriendId());
        }
        list.add(userId);

        QueryWrapper queryWrapper = new QueryWrapper();
        Page<UserInfo> page = new Page<>(0, 10);
        queryWrapper.notIn("id",list);
        queryWrapper.orderByAsc("RAND()");
        IPage selectPage = userInfoMapper.selectPage(page, queryWrapper);
        List<UserInfo> userInfoList = selectPage.getRecords();
        return userInfoList;
    }

}
